package com.dbq.fast.business.product.dialog;

import android.app.Dialog;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dbq.fast.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 */

public class PayAndLoginStatusDialog extends DialogFragment {
    private static final String DIALOG_TAG = "pay_status";
    public static final int SUCCESS = 9000;
    public static final int FAILED = 4000;
    public static final int NET_ERROR = 6002;
    public static final int CANCEL = 6001;
    public static final int UNDERWAR = 7002;//这个状态码为6000和8004和的一半，表示进行中
    //这里需要特殊说明一下，该dialog本来只处理支付结果状态相关的逻辑，但是为了处理账号在别的设备登陆问题，不再自定义一个Dialog，所以对该dialog扩展一种状态，要拿过来处理在其他设备登陆提示的Dialog。
    public static final int ACCOUNT_ON_OTHER_DEVICES_LOGIN = 8000;//账号在其他设备登陆了。

    public static final int GG_PAY_FAILED = 1000;


    public static final int Y_PAGE_HINT = 1030; //Y page hint
    public static final int UPDATE_VERSION = 1040; //Y page hint
    private static int CURRENT_STATUS = 0000;

    private int status;
    private String content;


    private static int TIME = 3;

    private Unbinder unbinder;
    private static OnCountDownListener countDownlistener;
    private static OnBottomBtnListener btmListener;
    private OnYListener ylistener;
    @BindView(R.id.tv_title)
    TextView titleTv;

    @BindView(R.id.iv_pay_success)
    ImageView ivPaySuccess;

    @BindView(R.id.tv_content)
    TextView contentTv;

    @BindView(R.id.tv_left)
    TextView leftTv;

    @BindView(R.id.tv_right)
    TextView rightTv;

    @BindView(R.id.center_line)
    View centerLine;

    @BindView(R.id.ll_bottom)
    LinearLayout bottomLl;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case SUCCESS:

                    --TIME;
                    if (TIME == 0) {
                        TIME = 3;
                        if (countDownlistener != null) {
                            countDownlistener.timeOut();
                        }
                        Dialog dialog = PayAndLoginStatusDialog.this.getDialog();
                        if (dialog != null && dialog.isShowing()) {
                            PayAndLoginStatusDialog.this.dismiss();
                        }
                    } else {
                        if (isResumed()) {
//                            setContent(TIME + getResources().getString(R.string.wait_back_main_page));
                            String content = String.format(getResources().getString(R.string.wait_back_main_page), String.valueOf(TIME));
                            SpannableStringBuilder style = new SpannableStringBuilder(content);
                            style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.pay_content)), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            setContent(style);
                        }
                        Message msg1 = obtainMessage();
                        msg1.what = SUCCESS;
                        sendMessageDelayed(msg1, 1000);
                    }

                    break;

            }

        }
    };


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0x00ffffff));
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_pay_status, container, true);
        unbinder = ButterKnife.bind(this, view);
        setPayStatus(status, content);
        getDialog().setCanceledOnTouchOutside(false);
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        status = getArguments().getInt("status");
        content = getArguments().getString("content");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        handler = null;
//        countDownlistener = null;
//        btmListener = null;
    }


    private static PayAndLoginStatusDialog newInstance(int status, String content) {
        PayAndLoginStatusDialog payAndLoginStatusDialog = new PayAndLoginStatusDialog();
        Bundle args = new Bundle();
        args.putInt("status", status);
        args.putString("content", content);
        payAndLoginStatusDialog.setArguments(args);

        return payAndLoginStatusDialog;
    }


    public static PayAndLoginStatusDialog show(FragmentManager fragmentManager, int status) {
        return show(fragmentManager, status, "");
    }

    public static PayAndLoginStatusDialog show(FragmentManager fragmentManager, int status, String content) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        PayAndLoginStatusDialog newFragment = PayAndLoginStatusDialog.newInstance(status, content);
        ft.add(newFragment, "pay_login_dialog");

        ft.commitAllowingStateLoss();
        // Create and show the dialog.


        return newFragment;
    }


    private void setPayStatus(int status, String content) {
        if (!isAdded()) return;
        switch (status) {
            case SUCCESS:
                setTitle(R.string.buy_success);
                content = String.format(getResources().getString(R.string.wait_back_main_page), String.valueOf(TIME));

                SpannableStringBuilder style = new SpannableStringBuilder(content);
                style.setSpan(new ForegroundColorSpan(this.getResources().getColor(R.color.pay_content)), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                setContent(style);
                ivPaySuccess.setBackgroundResource(R.drawable.ic_buy_success);
                contentTv.setGravity(Gravity.CENTER);
                setBottomVisible(View.GONE);
                Message msg = handler.obtainMessage();
                msg.what = SUCCESS;
                handler.sendMessageDelayed(msg, 1000);

                break;
            case FAILED:
                setTitle(R.string.pay_msg_title);
                SpannableStringBuilder style1 = new SpannableStringBuilder(getResources().getString(R.string.pay_failed_content));
                style1.setSpan(new ForegroundColorSpan(this.getResources().getColor(R.color.load_fail)), 26, 33, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                setContent(style1);
                setLeftTv(R.string.ok_left);
                setLeftVisible(View.VISIBLE);
                setLineVisible(View.GONE);
                setRightVisible(View.GONE);
                leftTv.setOnClickListener(v -> {
                    PayAndLoginStatusDialog.this.dismiss();
                });
                break;
            case NET_ERROR:
                setTitle(R.string.pay_msg_title);
                setContent(getResources().getString(R.string.net_error_of_pay));
                setRightTv(R.string.ok_left);
                setRightTv(R.string.leave_to_order_page);
                setLeftVisible(View.VISIBLE);
                setLineVisible(View.VISIBLE);
                setRightVisible(View.VISIBLE);
                leftTv.setOnClickListener(v -> {
                    PayAndLoginStatusDialog.this.dismiss();
                });
                rightTv.setOnClickListener(v -> {
                    if (btmListener != null) {
                        btmListener.goOrderPage();
                    }
                });

                break;
            case UNDERWAR:
                setTitle(R.string.pay_msg_title);
                setContent(getResources().getString(R.string.order_underwar));
                setLeftTv(R.string.back_main_page_right);
                setRightTv(R.string.leave_to_order_page);
                setLeftVisible(View.VISIBLE);
                setLineVisible(View.VISIBLE);
                setRightVisible(View.VISIBLE);
                leftTv.setOnClickListener(v -> {
                    if (btmListener != null) {
                        btmListener.goMainPage();
                    }
                });
                rightTv.setOnClickListener(v -> {
                    if (btmListener != null) {
                        btmListener.goOrderPage();
                    }
                });
                break;

            case CANCEL:
                setTitle(R.string.sure_cancel);
                setContent(getResources().getString(R.string.cancel_content));
                setLeftTv(R.string.sure_exit);
                setRightTv(R.string.Continue_buy);
                setLeftVisible(View.VISIBLE);
                setLineVisible(View.VISIBLE);
                setRightVisible(View.VISIBLE);
                leftTv.setOnClickListener(v -> {
                    if (btmListener != null) {
                        btmListener.cancel();
                    }

                    this.dismiss();
                });
                rightTv.setOnClickListener(v -> {
                    if (btmListener != null) {
                        btmListener.continuePay();
                        this.dismiss();
                    }
                });
                break;
            case ACCOUNT_ON_OTHER_DEVICES_LOGIN:
//                setTitle(R.string.title_dia);
                setContent(""/*getResources().getString(R.string.content_dia)*/);
//                setLeftTv(R.string.left_main);
//                setRightTv(R.string.right_login);
                setLeftVisible(View.VISIBLE);
                setLineVisible(View.VISIBLE);
                setRightVisible(View.VISIBLE);
                leftTv.setOnClickListener(v -> {
                    if (btmListener != null) {
                        btmListener.goMainPage();
                    }
                });
                rightTv.setOnClickListener(v -> {
                    if (btmListener != null) {
                        btmListener.goLoginPage();
                    }
                });
                break;

            case GG_PAY_FAILED:
                setTitle(R.string.pay_msg_title);
                SpannableStringBuilder style2 = new SpannableStringBuilder(getResources().getString(R.string.google_pay_failed));

                setContent(style2);
                setLeftTv(R.string.ok_left);
                setLeftVisible(View.VISIBLE);
                setLineVisible(View.GONE);
                setRightVisible(View.GONE);
                leftTv.setOnClickListener(v -> {
                    if (btmListener != null) {
                        btmListener.goMainPage();
                    }
                });
                break;

            case Y_PAGE_HINT:
                setTitle(R.string.hint);
                setContent(getResources().getString(R.string.y_content));
                setLeftTv(R.string.no_effect_me);
                setRightTv(R.string.immediately_buy);
                setLeftVisible(View.VISIBLE);
                setLineVisible(View.VISIBLE);
                setRightVisible(View.VISIBLE);
                leftTv.setOnClickListener(v -> {
                    if (ylistener != null) {
                        ylistener.cancel();
                    }

                    this.dismiss();
                });
                rightTv.setOnClickListener(v -> {
                    if (ylistener != null) {
                        ylistener.nextPage();
                        this.dismiss();
                    }
                });
                break;

            case UPDATE_VERSION:
                setTitle(R.string.update_hint);
                setContent(content);
                setLeftTv(R.string.cancel);
                setRightTv(R.string.update);
                setLeftVisible(View.VISIBLE);
                setLineVisible(View.VISIBLE);
                setRightVisible(View.VISIBLE);
                leftTv.setOnClickListener(v -> {
                    if (ylistener != null) {
                        ylistener.cancel();
                    }

                    this.dismiss();
                });
                rightTv.setOnClickListener(v -> {
                    if (ylistener != null) {
                        ylistener.nextPage();
                        this.dismiss();
                    }
                });
                break;
        }
    }

    private void setTitle(int strId) {
        if (titleTv != null) {
            titleTv.setText(strId);
        }
    }

    private void setContent(SpannableStringBuilder style) {
        if (contentTv != null) {
            contentTv.setText(style);
        }
    }

    private void setContent(String content) {
        if (contentTv != null) {
            contentTv.setText(content);
        }
    }

    private void setRightTv(int strId) {
        if (rightTv != null) {
            rightTv.setText(strId);
        }
    }

    private void setLeftTv(int strId) {
        if (leftTv != null) {
            leftTv.setText(strId);
        }
    }

    private void setLineVisible(int visible) {
        if (centerLine != null) {
            centerLine.setVisibility(visible);
        }
    }

    private void setRightVisible(int visible) {
        if (rightTv != null) {
            rightTv.setVisibility(visible);
        }
    }

    private void setLeftVisible(int visible) {
        if (leftTv != null) {
            leftTv.setVisibility(visible);
        }
    }

    private void setBottomVisible(int visible) {
        if (bottomLl != null) {
            bottomLl.setVisibility(visible);
        }
    }

    public static void setOnCountDown(OnCountDownListener listener) {
        countDownlistener = listener;
    }

    public interface OnCountDownListener {
        void timeOut();
    }

    public static void setBottomBtn(OnBottomBtnListener listener) {
        btmListener = listener;
    }

    public interface OnBottomBtnListener {
        void continuePay();

        void goMainPage();

        void goOrderPage();

        void goLoginPage();

        void cancel();

    }


    public void setYListener(OnYListener listener) {
        this.ylistener = listener;
    }

    public interface OnYListener {
        void nextPage();

        void cancel();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        countDownlistener = null;
        btmListener = null;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // super.onSaveInstanceState(outState); 不保存用户状态
    }
}
